#!/usr/bin/env node
import { program } from "commander";
import { buildCreatePrUrl, getBranches } from "../utils/git";
import { pickup } from "../utils/input";
import { openUrl } from "../utils/system";

program
  .command("", { isDefault: true })
  .description("Create pr from current branch to target branch")
  .option("-t, --target <string>", "target branch", "develop")
  .option("-s, --select", "select target branch", false)
  .option(
    "-k, --keyword <string>",
    "keyword of target branch(use `,` to split)",
    ""
  )
  .action(run)
  .parse(process.argv);

interface Args {
  target: string;
  keyword?: string;
  select: boolean;
}

async function run({ target, select, keyword }: Args) {
  if (select) {
    const branches = await getBranches((keyword ?? "") + ",remotes");
    const choices = branches.map((choice) =>
      choice.replace(/^remotes\/origin\//, "")
    );
    target = await pickup(choices);
  }

  await buildCreatePrUrl(target).then(openUrl);
}
